package vn.com.aptech.msh.business;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import vn.com.aptech.msh.entities.Role;
import vn.com.aptech.msh.entities.User;
import vn.com.aptech.msh.utils.MD5Utility;

/**
 *
 * @author trietto
 */
@Stateless
public class UserBean implements IUserBean {

    @PersistenceContext(unitName = "MySweetHome-ejbPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public UserBean() {
        //super(User.class);
    }

    @Override
    public User authenticate(String username, String password) {
        try {
            String hashedPassword = MD5Utility.hash(password);
            /*String queryString = "Select u from User u where u.username=:username and u.password=:password";
            Query query = em.createQuery(queryString).setParameter("username", username).setParameter("password", hashedPassword);
            return (User) query.getSingleResult();*/

            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<User> cq = cb.createQuery(User.class);
            Root<User> user = cq.from(User.class);
            cq.select(user);
            cq.where(cb.and(cb.equal(user.get("username"), username), cb.equal(user.get("password"), hashedPassword)));

            TypedQuery<User> query = em.createQuery(cq);
            List<User> users = query.getResultList();
            if (users == null || users.isEmpty()) {
                return null;
            } else {
                return users.get(0);
            }

        } catch (Exception ex) {
            Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    @Override
    public User changePassword(User user, String newPassword) {
        try {
            User entity = user;
            entity.setPassword(MD5Utility.hash(newPassword));
            return em.merge(entity);
        } catch (Exception ex) {
            Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    @Override
    public User updateProfile(User entity) {
        try {
            return em.merge(entity);
        } catch (Exception ex) {
            Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    @Override
    public void registerUser(User entity, int roleId) {
        try {
            entity.setPassword(MD5Utility.hash(entity.getPassword()));
            Role role = em.find(Role.class, roleId);
            entity.setRole(role);
            em.persist(entity);
        } catch (Exception ex) {
            Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public boolean isUsernameExists(String username) {
        try {
            String queryString = "Select u from User u where u.username=:username";
            Query query = em.createQuery(queryString).setParameter("username", username);
            List result = query.getResultList();
            if (result == null || result.isEmpty()) {
                return false;
            } else {
                return true;
            }
        } catch (Exception ex) {
            Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

    @Override
    public boolean isEmailExist(String email) {
        try {
            String queryString = "Select u from User u where u.email=:email";
            Query query = em.createQuery(queryString).setParameter("email", email);
            List result = query.getResultList();
            if (result == null || result.isEmpty()) {
                return false;
            } else {
                return true;
            }
        } catch (Exception ex) {
            Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

    @Override
    public int getUsersCount() {
        Query query = em.createQuery("SELECT COUNT(u.userID) FROM User u");
        Number countResult = (Number) query.getSingleResult();
        return countResult.intValue();
    }
}
